<?php


namespace app\service\model;


use app\model\system\Menu;
use app\service\Y;

class AdminModel extends BaseModel
{
    protected $table = 'admin';

    /**
     * 检查管理员权限
     * @param $url
     * @param $roles
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function checkAuth ($url, $roles): bool
    {
        $auth_info = AdminAuthorityModel::getAuthByUrl($url);
        if ($auth_info) {
            $role_ids = AdminRoleModel::getAuths($roles);
            if (in_array($auth_info->id, $role_ids)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     *
     * @param $param
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveAdmin($param, $id): \think\response\Json
    {
        if ($id > 0) {

            if (self::where('username', '=', $param['username'])->where('id', '<>', $id)->find()) {
                return Y::error('用户名已存在');
            }

            $admin = self::find($id);
            if (!$admin) {
                return Y::error('参数错误');
            }

            if ($password = input('param.password', '')) {
                $param['password'] = md5($password . $admin->salt);
            }
            $admin->save($param);
        } else {
            $param['salt'] = random_keys(6);
            $param['password'] = md5($param['password'] . $param['salt']);
            self::create($param);
        }

        return Y::success([], '保存成功');
    }
}